package com.geostar.tbsdemo;

import android.Manifest;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

//import com.artifex.mupdf.mini.DocumentActivity;
import com.artifex.mupdf.viewer.DocumentActivity;
import com.tencent.smtt.sdk.*;

import java.io.File;
import java.util.HashMap;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

import static com.geostar.tbsdemo.TBSTestApplication.FILE_DIR;

public class MainActivity extends AppCompatActivity {

    private static final int RC_WRITE_STOREGE = 1;
    protected WebView tbsWebView;
    protected Button btnOpenfile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        super.setContentView(R.layout.activity_main);
        initView();
        tbsWebView.loadUrl("file:///android_asset/test.html");
        String[] perms = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        EasyPermissions.requestPermissions(
                new PermissionRequest.Builder(this, RC_WRITE_STOREGE, perms)
                        .setRationale("请求权限")
                        .setPositiveButtonText("确认")
                        .setNegativeButtonText("取消")
                        .build());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(RC_WRITE_STOREGE)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            // ...
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "请求权限",
                    RC_WRITE_STOREGE, perms);
        }
    }

    private void initView() {
        tbsWebView = (WebView) findViewById(R.id.tbs_webView);
//        tbsWebView.setLayerType(View.LAYER_TYPE_HARDWARE);
        tbsWebView.setDrawingCacheEnabled(true);
        btnOpenfile = (Button) findViewById(R.id.btn_openfile);
        btnOpenfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = new File(Environment.getExternalStorageDirectory(), "Downloads/largepdf2.pdf").getAbsolutePath();
//                TBSFileViewActivity.viewFile(MainActivity.this, "/sdcard/Downloads/largepdf2.pdf");
                startMuPDFActivityWithExampleFile(fileName);
//                openFile("/sdcard/Downloads/largepdf.pdf2");
            }
        });
        findViewById(R.id.btn_openfile_with_tbs).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = new File(Environment.getExternalStorageDirectory(), "Downloads/largepdf2.pdf").getAbsolutePath();
//                startMuPDFActivityWithExampleFile(fileName);
                openFile(fileName);
            }
        });
        findViewById(R.id.btn_openfile_with_tbs_self).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = new File(Environment.getExternalStorageDirectory(), "Downloads/largepdf2.pdf").getAbsolutePath();
                TBSFileViewActivity.viewFile(MainActivity.this, fileName);
            }
        });
        findViewById(R.id.btn_openfile_doc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFile(FILE_DIR + "TestDoc.doc");
            }
        });
        findViewById(R.id.btn_openfile_ppt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFile(FILE_DIR + "TestPPT.ppt");
            }
        });
        findViewById(R.id.btn_openfile_excel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFile(FILE_DIR + "TestExcel.xls");
            }
        });

        findViewById(R.id.btn_openfile_online).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                openFile(FILE_DIR + "TestExcel.xls");
                TBSFileViewActivity2.viewFile(MainActivity.this, FILE_DIR + "像艺术家一样思考.pdf",
                        "http://192.168.31.34:8080/files/像艺术家一样思考.pdf");
            }
        });


    }

    private void viewByMUPDF() {

    }

    public void startMuPDFActivity(Uri documentUri) {
        Intent intent = new Intent(this, DocumentActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(documentUri);
        startActivity(intent);
    }

    public void startMuPDFActivityWithExampleFile(String fileName) {
        File dir = Environment.getExternalStoragePublicDirectory
                (Environment.DIRECTORY_DOWNLOADS);
//        File file = new File(dir, fileName);
        File file = new File(fileName);
        if (!file.isFile()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        Uri uri = Uri.fromFile(file);
        startMuPDFActivity(uri);
    }

    private void openFile(String filePath) {
        File file = new File(filePath);
//        TBSFileViewActivity2.viewFile(this, file.getAbsolutePath(), null);
        QbSdk.openFileReader(this, file.getAbsolutePath(), getHashMap(), new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {

            }
        });

    }

    @NonNull
    private HashMap<String, String> getHashMap() {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("local", "true");
        stringStringHashMap.put("style", "1");
        stringStringHashMap.put("menuData", jsondata);
        return stringStringHashMap;
    }

    public static final String jsondata = "{ pkgName:\"com.geostar.tbsdemo\", "
            + "className:\"com.geostar.tbsdemo.FileActivity\","
            + "thirdCtx: {pp:123},"
            + "menuItems:"
            + "["
            + "{id:0,iconResId:" + R.mipmap.ic_launcher + ",text:\"menu0\"},{id:1,iconResId:" + R.mipmap.ic_launcher + ",text:\"menu1\"}, {id:2,iconResId:" + R.mipmap.ic_launcher + ",text:\"菜单2\"}" + "]" + "}";

    /*

    点击菜单项后intent 参数：
    Bundle[{menuId=0, filePath=/sdcard/Downloads/oracle客户端安装.docx, thirdCtx={"pp":123}}]
    action =  ReaderSdkMenuClicked
     */
    private String createFileUrl() {
        File file = new File("/sdcard/Downloads/测试.docx");
        return Uri.fromFile(file).toString();
    }

}
